from django.shortcuts import render
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import Cluster, Node, Instance, ResourceUsage
from .serializers import (
    ClusterSerializer, NodeSerializer,
    InstanceSerializer, ResourceUsageSerializer
)

# Create your views here.

class ClusterViewSet(viewsets.ModelViewSet):
    queryset = Cluster.objects.all()
    serializer_class = ClusterSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

class NodeViewSet(viewsets.ModelViewSet):
    queryset = Node.objects.all()
    serializer_class = NodeSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        queryset = Node.objects.all()
        cluster_id = self.request.query_params.get('cluster_id', None)
        if cluster_id is not None:
            queryset = queryset.filter(cluster_id=cluster_id)
        return queryset

class InstanceViewSet(viewsets.ModelViewSet):
    queryset = Instance.objects.all()
    serializer_class = InstanceSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        queryset = Instance.objects.all()
        node_id = self.request.query_params.get('node_id', None)
        if node_id is not None:
            queryset = queryset.filter(node_id=node_id)
        return queryset

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['post'])
    def record_usage(self, request, pk=None):
        instance = self.get_object()
        serializer = ResourceUsageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(instance=instance)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ResourceUsageViewSet(viewsets.ModelViewSet):
    queryset = ResourceUsage.objects.all()
    serializer_class = ResourceUsageSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        queryset = ResourceUsage.objects.all()
        instance_id = self.request.query_params.get('instance_id', None)
        if instance_id is not None:
            queryset = queryset.filter(instance_id=instance_id)
        return queryset
